import cv2
import numpy as np

def homomorphic_filter(src, d0=10, r1=0.5, rh=2, c=4, h=2.0, l=0.5):
    '''
    https://blog.csdn.net/qq_38463737/article/details/118756133?ops_request_misc=&request_id=&biz_id=102&utm_term=opencv-python%20%E5%90%8C%E6%80%81%E6%BB%A4%E6%B3%A2&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-8-118756133.142^v9^pc_search_result_control_group,157^v4^control&spm=1018.2226.3001.4187
    '''
    gray = src.copy()
    if len(src.shape) > 2:
        gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    gray = np.float64(gray)
    rows, cols = gray.shape

    gray_fft = np.fft.fft2(gray)
    gray_fftshift = np.fft.fftshift(gray_fft)
    dst_fftshift = np.zeros_like(gray_fftshift)
    M, N = np.meshgrid(np.arange(-cols // 2, cols // 2), np.arange(-rows // 2, rows // 2))
    D = np.sqrt(M ** 2 + N ** 2)
    Z = (rh - r1) * (1 - np.exp(-c * (D ** 2 / d0 ** 2))) + r1
    dst_fftshift = Z * gray_fftshift
    dst_fftshift = (h - l) * dst_fftshift + l
    dst_ifftshift = np.fft.ifftshift(dst_fftshift)
    dst_ifft = np.fft.ifft2(dst_ifftshift)
    dst = np.real(dst_ifft)
    dst = np.uint8(np.clip(dst, 0, 255))
    return dst

def filter_out_red(src_frame):
    if src_frame is not None:
        hsv = cv2.cvtColor(src_frame, cv2.COLOR_BGR2HSV)
        lower_red = np.array([156, 43, 46])
        upper_red = np.array([180, 255, 255])
        # inRange()方法返回的矩阵只包含0,255 (CV_8U) 0表示不在区间内
        mask = cv2.inRange(hsv, lower_red, upper_red)
        return cv2.bitwise_and(src_frame, src_frame, mask=mask)

def max2min(gray):
    gray[gray == 255] = 0
    return gray
img = cv2.imread('d00071_1_0_88.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
y = yuv[:, :, 0]
# gray2 = gray[112:234, 437:501]
# clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
# cl1 = clahe.apply(gray)
# IOU = cl1[112:173, 501:]
# IOU_gray = cv2.cvtColor(IOU, cv2.COLOR_BGR2GRAY)
#
red = filter_out_red(img)

y_mm = max2min(y)
y_eq = cv2.equalizeHist(y)
# retval, dst = cv2.threshold(IOU, 0, 255, cv2.THRESH_OTSU)
# retval, dst = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY)

# dst = homomorphic_filter(y, d0=10, r1=0.5, rh=2, c=4, h=2.0, l=0.5)
yuv2 = yuv.copy()
yuv2[:, :, 0] = y_eq
bgr = cv2.cvtColor(yuv2, cv2.COLOR_YUV2BGR)
# cv2.imshow('dst', dst)
# cv2.imshow('src', gray)
cv2.imshow('img', img)
cv2.imshow('bgr', bgr)
# cv2.imshow('iou', IOU)
# cv2.imshow('cl1', cl1)
# cv2.imshow('red', red)
cv2.imshow('mm', y_mm)
cv2.waitKey(0)
cv2.destroyAllWindows()